package com.tengju.data.infrastructure.shared;


import com.fasterxml.jackson.core.type.TypeReference;
import com.idanchuang.dc.open.data.sdk.base.*;
import com.tengju.data.domain.shared.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @author wuziyang
 */
@Slf4j
@Component
public class OpenPlatformUtil {

    public static final String SMS_API = "tengju.sms";

    public static final String USER_API = "userInfoList";
    public static final String USER_BY_ID_CODE_API = "userInfo.byIdCodes";
    public static final String STORE_TOKEN_API = "abm.storeToken";
    public static final String DELETE_TOKEN_API = "abm.delToken";

    public static final String IDENTITY_GET_API = "identity.get";
    public static final String CONTRACT_GET_API = "contract.get";

    public static final String STAR_CHANGE_COUNT_API = "starChange.count";
    public static final String STAR_CHANGE_LIST_API = "starChange.list";
    public static final String STAR_INDICATOR_LIST_API = "starIndicator.list";
    public static final String STAR_USER_INSERT_API = "abm.insertUserInfo";


    public static final String STORE_MARKET_PROFIT_MID_INFO_API = "marketProfit.saveMidInfoSnapshot";
    public static final String STORE_MARKET_PROFIT_MID_INFO_MONTH_API = "marketProfit.saveMidInfoMonthSnapshot";
    public static final String QUERY_MARKET_PROFIT_DATA_VERSION_API = "marketProfit.getDataVersion";
    public static final String COUNT_MARKET_PROFIT_API = "marketProfit.countMidInfo";
    public static final String QUERY_MARKET_PROFIT_API = "marketProfit.getMidInfo";
    public static final String QUERY_MARKET_PROFIT_TEMPLATE_API = "marketProfit.getTemplate";
    public static final String STORE_MARKET_PROFIT_API = "marketProfit.save";
    public static final String DELETE_MARKET_PROFIT_API = "marketProfit.delByVersion";


    /**
     * 私钥
     */
    static String appPriRsaKey;
//            = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCnWnCKM/lO8n3roOyv4l2P7BiO" +
//            "LdbtjK3YT4p49OQtHBRrwl5PaorQn4tNvy2qTmb6bHhNnfTeJQZSgb3yyUXBvIHyFDXSFtnttkVg" +
//            "ZCsJKw8S8i4G6ZQP3J+jjxOv/09VkjCOHn/RqEj7SOQY5ZvJ0GaEzRchdo4rLnoZy7/VIicxkWTO" +
//            "ayR+KOA85AZyifX4NxEVxxZcQaeJ55JAsDPqYBpcOOECi9WROB2WbYs4w2CNiwviW1pRxnS90HT/" +
//            "KoZb1dBpvvBgI524caJYK4juVuRc0TYd7NpNYYVUTm6/BDpii8/qCa6J2+KFe1zz12Rvhz3iPABN" +
//            "jJ7ruh+wSeA/AgMBAAECggEAJEaoamzFt+U8gl0JsT6CRXZKBFfPZQK/lEn5nCqJY3XYv1sMkm5n" +
//            "1L0gtyOfxHDmRZZJpZl9wMGJ00yoXf5fDpXMHStgVz/40VxXQYO1CHG6/MJeU8VCAQYz3IJhJB9V" +
//            "lRjxSX02+71cxIuSVgs/b8mqz1KdlvVZ7+ZNNVZDKPG5GcZ+O6VJeFpY0HlOKSa99ZhL7a6mRjHn" +
//            "KyOcn1j3daWcgDDPDImDYH9jAbXeJuzfvooiaIWCSRWou2g58P9YzGuUyRdkzfqmj958hWrzXJFb" +
//            "rXLuJ+S8c/ZO3CLcrW/fV3lSztHq94rVmiLj2u9q/cAINqg/Ab3MLx4cLcXD4QKBgQD3s9mHoMnd" +
//            "GjVD4I21NA/2gZRJGjJ/pqiALlY55p7m4DiO/Dp8dCPWqAg+WQnUzRNaB4PYvSWfR09TS2MwFuxW" +
//            "syDzJKt7HbqoGKZZOPW/MZE82qXhpm/vyG3fO+VW0ZOeZ5k9CHoEjBA4uhKRGqifWRZ6QetC2QIG" +
//            "hSzg4X2qFwKBgQCs9Y/uJq7GMIY0ebVh4wYkSpbJv8cefz688g+1pRzRzdahJbpJ7wW2k4DmwKvn" +
//            "yF3pabO2JJlC+iz/VTddCF5NbuPEpEHhgI3//qKpB264DMU3qIrGICTu+dHBXtcBEnG2aQFPOra8" +
//            "hrgk9zDApIor5FMs0VvrOkjSVpSJz7xcGQKBgQDNWEGLWFZAf4uMu8l+YKyjFIUTnS4j+MtTiBZf" +
//            "Zbpxd4wrrRnnNnjHaQF8fl/SFDhouDYrJZLc2kb+rE6L/VTsAw/bwZiPNfQZimXNLZU8bSEUK8a8" +
//            "rDe7tpKvL35OXOtdtFCq8i4FOv/vpwHhXRJRF4+0xpT8E97D/P9ZZlXA/QKBgQCFu0UzfcNrSH+s" +
//            "OWLusevAyc93ZQpf4UEwNPXCnE0BR+epKBO3MNI5Din/wX/psnoyjOFAd2HtcKS0ND6fd2X69z+z" +
//            "ftHVu2GQS2GX0kBgnLcsxuuuL5J/GLh/jIYvtQQpZ1101lAOyxe8tUiD23VeZKePIr2wzpsZz4oA" +
//            "WJgqmQKBgQDsUBg/aG4kjTVTELGqecNyb1vhP6y3yZfMsNnyAgv96WBPzHPeT9VcKa2X3T9iRpsp" +
//            "SY8J2P/9eNvFFKJZH8z6aDP+n+KUr/EIJustvfNzJpkiP6ChljwWLab53KI2y4znYSbd97L44E3+" +
//            "+LF1ZMI9Jf+c8Eqblvmpa2mz10y9WQ==";

    /**
     * 数据开放平台 rsa 公钥
     */
    static String pubRsaKey;

//    = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgHE9+hPKcIi9Lq2yLKbEzM" +
//            "cQtS7BZbHiXfmDJuhIR4rkI8YOz66Uu72EZbGGGRIH5cZqQztJ5VRFgvYYruEsGMlq+UOPe7yqAzo" +
//            "EYXLl5LaOoE4PLWHd0wxdFhgLr7HueT1jBJieD5OvakzjoaHqGIoYGR6OY8Ol6dhllDwjd2nCbqhH" +
//            "delI0xcsHcy2CIJRt/dQ5tkX4NiWjv02AHwQHAMKC75+2BVDqsWsEHuTG4WAPoAyFVC5fL4G+MYxR" +
//            "jFXKcBh9NIZd4U3SmAy5pD0p6VALHVzzb5goXfnmus1gZF2lYcGMl+kzfj7GEMotRJtkF5pIVEVoX" +
//            "eyGrAlKTcYwwIDAQAB";

    /**
     * 请求开放平台地址
     */
    static String serverUrl;

    static String appKey;

    static String secretKey;

    private static final int CONN_TIMEOUT = 30000;
    private static final int READ_TIMEOUT = 30000;


    @Value("${openPlatform.appPriRsaKey}")
    public void setAppPriRsaKey(String appPriRsaKey) {
        OpenPlatformUtil.appPriRsaKey = appPriRsaKey;
    }

    @Value("${openPlatform.pubRsaKey}")
    public void setPubRsaKey(String pubRsaKey) {
        OpenPlatformUtil.pubRsaKey = pubRsaKey;
    }

    @Value("${openPlatform.serverUrl}")
    public void setServerUrl(String serverUrl) {
        OpenPlatformUtil.serverUrl = serverUrl;
    }

    @Value("${openPlatform.appKey}")
    public void setAppKey(String appKey) {
        OpenPlatformUtil.appKey = appKey;
    }

    @Value("${openPlatform.secretKey}")
    public void setSecretKey(String secretKey) {
        OpenPlatformUtil.secretKey = secretKey;
    }

    public static ApiResponse submitEncryption(String api, Object requestData) {

        // 1. 构造配置
        DcConfig dcConfig = new DcConfig(serverUrl, appKey, secretKey,CONN_TIMEOUT,READ_TIMEOUT);
        EncryptConfig encryptConfig = new EncryptConfig(appPriRsaKey, pubRsaKey);

        // 2. 构造client，传入 encryptConfig 之后默认加密
        DcOpenDataClient encryptClient = DcOpenDataClientFactory.create(dcConfig, encryptConfig);

        // 3. 发起请求
        String bizResponseJsonStr;
        try {
            String reqData = JsonUtil.toJSONString(requestData);
            bizResponseJsonStr = encryptClient.invoke(api, reqData);

            log.info("请求成功:{}，参数：{}", reqData, api);

            ApiResponse apiResponse = JsonUtil.toObject(bizResponseJsonStr, ApiResponse.class);

            return apiResponse;

        } catch (DcOpenDataException e) {
            throw new InfraException("开放平台调用失败，errCode: " + e.getErrCode() + "; errMsg: " + e.getErrMsg());
        }
    }

    public static <T> T convertData(Class<T> clazz, ApiResponse apiResponse) {

        String dataString = JsonUtil.toJSONString(apiResponse.getData());
        return JsonUtil.toObject(dataString, clazz);

    }

    public static <T> List<T> convertData(TypeReference<List<T>> typeReference, ApiResponse apiResponse) {
        String resultJson = JsonUtil.toJSONString(apiResponse.getData());
        return JsonUtil.toList(resultJson, typeReference);
    }


}
